Directives Filtering

Course- AngularJS >

Some of the directives covered above support filtering. This section will explain how filtering works.

The ng-repeat directive can accept a filter like this:

<div ng-repeat="item in myData.items | filter: itemFilter"></div>

Notice the | filter: itemFilter part of the declaration above. That part is the filter definition. The | filter: part tells AngularJS to apply a filter to the myData.items array. The itemFilter is the name of the filter function. This function has to be present on the $scope object, and it has to return either true or false. If the filter function returns true, then the element from the array is used by the ng-repeat directive. If the filter function returns false, the element is ignored. Here is an example:

<script>
  angular.module("myapp", [])
    .controller("MyController", function($scope) {
      $scope.myData = {};
      $scope.myData.items  = [ {text : "one"}, {text : "two"}, {text : "three"}, {text : "four"} ];

      $scope.itemFilter = function(item) {
        if(item.text == "two") return false;
          return true;
        }
      }
    });
</script>

Formatting Filters

AngularJS comes with a set of built-in formatting filters which can be used in conjunction with the interpolation directive, and with ng-bind. Here is a list of the formatting filters:

Filter Description
date Formats the variable as a date according to the given date format
currency Formats the variable as a number with a currency symbol
number Formats the variable as a number
lowercase Converts the variable to lowercase
uppercase Converts the variable to uppercase
json Converts the variable to a JSON string

Here is a date filter example:

<span>{{myData.theDate | date: 'dd-MM-yyyy'}}</span>

This example shows the date filter which can format a JavaScript date object according to the date format pattern given after the | date: part. It is the myData.theDate property that will be formatted as a date. Thus, it has to be a JavaScript date object.

Here is a number filter example:

<span>{{myData.theNumber | number: 2}}</span>

This example formats the myData.theNumber variable as a number with 2 decimal places.

Here are an lowercase and uppercase filter example:

<span>{{myData.mixedCaseText | lowercase}}</span>
<span>{{myData.mixedCaseText | uppercase}}</span>

Array Filters

AngularJS also contains a set of array filters which filters or transforms arrays. These filters are:

Array Filters:

Filter Description
limitTo Limits the array to the given size, beginning from some index in the array. The limitTo filter also works on strings.
filter A general purpose filter.
orderBy Sorts the array based on provided criteria.

Here is a limitTo example:

<span>{{myData.theText | limitTo: 3}}</span>

This limits the $scope myData.theText variable to a length of 3 characters. If this filter had been applied to an array, the array would have been limited to 3 elements.

The filter filter is a special filter which can do a lot of different things. In its simplest form it simply calls a function on the $scope object. This function must return true or false. True is returned if the filter accepts the value passed to it. False is returned if the filter cannot accept the value. If the filter cannot accept the value, the value is not included in the array resulting from the filtering. Here is an example:

<ol>
    <li ng-repeat="item in myData.items | filter:filterArray">
        {{item.text}} : {{$first}}, {{$middle}}, {{$last}}
    </li>
</ol>
<script>
    angular.module("myapp", [])
        .controller("MyController", function($scope) {
            $scope.myData = {};
            $scope.myData.items    = 
                [ {text : "one"}, {text : "two"}, {text : "three"}, {text : "four"} ];

            $scope.filterArray = function(item) {
                if(item.text == "two") return false;
                return true;
            }
        } );
</script>

This example calls the filterArray() function which filters out items which has a text property with the value two.

Here is an orderBy example:

<ol>
    <li ng-repeat="item in myData.items | orderBy:sortField:reverse">
        {{item.text}} : {{$first}}, {{$middle}}, {{$last}}
    </li>
</ol>
    
<script>
    angular.module("myapp", [])
            .controller("MyController", function($scope) {
                $scope.myData = {};
                $scope.myData.items    = [ {text : "one"}, {text : "two"}, {text : "three"}, {text : "four"} ];
                $scope.sortField = "text";
                $scope.reverse   = true;
            } );
</script>

The orderBy filter takes a $scope variable as parameter. In this example that variable is named sortField. The value of this variable is the name of the property on the sorted data objects which is used to sort the data objects. In this example the sortField property is set to text which means that the data object's text property is used to sort the data objects.

The orderBy filter can also take a second $scope variable as parameter. In this example that variable is named reverse. The value of this variable determines if the data objects are to be sorted in their natural order, or the reverse order of that. In this case the reverse variable is set to true, meaning the data objects will be sorted in reverse order.

Chaining Filters

It is possible to chain filters by simply putting more filters after each other in the filter section. When chaining filters, the output of one filter is used as input for the next filter in the chain. Here is an example:

<span>{{myData.theText | limitTo: 5 | uppercase}}</span>

This example first limits the string myData.theText to 5 characters using the limitTo filter, and the converts the 5 characters to uppercase using the uppercase filter.

Assigning Filter Output To Variables

It is possible to assign the output of a filter to a temporary variable which you can then refer to later in your view. Here is an example:

<ol>
    <li ng-repeat="item in filteredItems = ( myData.items | filter:filterArray) ">
        {{item.text}} : {{$first}}, {{$middle}}, {{$last}}
    </li>
</ol>
<div>{{filteredItems.length}}</div>

This example assigns the output of the filtering to the filteredItems variable. The example then refers to this variable inside the {{ }} directive under the ol element.

Implementing Custom Filters

You can implement your own filters in case the AngularJS filters do not suit your needs. Here is an example:

<div>Filtered: {{myData.text | myFilter}}</div>
    
    
<script>
    var module = angular.module("myapp", []);

    module.filter('myFilter', function() {

        return function(stringValue) {
            return stringValue.substring(0,3);
        };
    });
</script>    

This example registers a filter with AngularJS which can filter strings. The filter returns the first 3 characters of the string. The filter is registered with the name myFilter. It is this name you will have to use when referencing the filter, as you can see in the beginning of the filter.

If your filter needs more input parameters, add more parameters to the filter function, and add the parameters after the filter name and a : when referencing it. Here is an example:

<div>Filtered: {{myData.text | myFilter:2:5}}</div>

<script>
    var module = angular.module("myapp", []);

    module.filter('myFilter', function() {

        return function(stringValue, startIndex, endIndex) {
            return stringValue.substring(parseInt(startIndex), parseInt(endIndex));
        };
    });
</script>

Notice how the filter reference (| myfilter:2:5) now has two values after the filter name, each value separated by a colon. These two values are passed to the filter as parameters. Notice also how the filter function now takes two extra parameters named startIndex and endIndex. These two parameters are used to determine which part of the string to return as substring from the filter.